package io.terminus.lego.shinda.web.security.handler

import io.terminus.lego.shinda.web.security.email.exception.EmailAuthenticationException
import io.terminus.lego.shinda.web.security.phone.exception.SmsAuthenticationException
import io.terminus.lego.shinda.web.security.special_user.exception.SpecialUserAuthenticationException
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.stereotype.Component
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 登录失败处理
 * @author wangmeng
 * @date 2018/4/12
 */
@Component
class UCAuthenticationFailureHandler : AuthenticationFailureHandler {
    /**
     * 默认登录失败时会302到错误页，这里直接返回json
     */
    private val handleFailurePath = "/api/login/failure"

    override fun onAuthenticationFailure(request: HttpServletRequest, response: HttpServletResponse, exception: AuthenticationException) {
        var msg = "username or password mismatch"
        if (exception is SmsAuthenticationException
                || exception is EmailAuthenticationException
                || exception is SpecialUserAuthenticationException) {
            msg = exception.message!!
        }
        request.setAttribute("error", msg)
        request.getRequestDispatcher(handleFailurePath).forward(request, response)

    }
}